<template>
  <div class="table-container">
    <h1>数据表格</h1>
    
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
        placeholder="请输入关键字搜索"
        v-model="searchQuery"
        class="search-input"
        clearable
        @clear="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>
    
    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
      <el-table-column prop="name" label="名称" width="120"></el-table-column>
      <el-table-column prop="category" label="分类"></el-table-column>
      <el-table-column prop="price" label="价格" sortable>
        <template slot-scope="scope">
          ¥{{ formatPrice(scope.row.price) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '可用' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    
    <!-- 查看详情对话框 -->
    <el-dialog title="详细信息" :visible.sync="dialogVisible" width="30%">
      <div v-if="currentRow">
        <p><strong>ID:</strong> {{ currentRow.id }}</p>
        <p><strong>名称:</strong> {{ currentRow.name }}</p>
        <p><strong>分类:</strong> {{ currentRow.category }}</p>
        <p><strong>价格:</strong> ¥{{ formatPrice(currentRow.price) }}</p>
        <p><strong>创建时间:</strong> {{ currentRow.createTime }}</p>
        <p><strong>状态:</strong> {{ currentRow.status }}</p>
        <p><strong>描述:</strong> {{ currentRow.description }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { tableDataApi } from '@/api/tableData';

export default {
  name: 'TableData',
  data() {
    return {
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchQuery: '',
      dialogVisible: false,
      currentRow: null
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 格式化价格显示
    formatPrice(price) {
      if (price === null || price === undefined) {
        return '0.00';
      }
      // 确保price是数字
      const numPrice = Number(price);
      return isNaN(numPrice) ? '0.00' : numPrice.toFixed(2);
    },
    
    // 获取表格数据
    fetchData() {
      this.loading = true;
      const params = {
        page: this.currentPage - 1, // 后端页码从0开始
        size: this.pageSize,
        sort: 'id',
        direction: 'ASC',
        search: this.searchQuery || undefined
      };
      
      tableDataApi.getList(params)
        .then(response => {
          this.tableData = response.content;
          this.total = response.totalElements;
        })
        .catch(error => {
          console.error('获取数据失败:', error);
          this.$message.error('获取数据失败，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    
    // 处理搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    
    // 查看详情
    handleView(row) {
      this.currentRow = row;
      this.dialogVisible = true;
    },
    
    // 编辑行
    handleEdit(row) {
      // 这里可以打开编辑对话框
      this.$message({
        message: `编辑ID为${row.id}的数据`,
        type: 'info'
      });
    },
    
    // 删除行
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        tableDataApi.delete(row.id)
          .then(() => {
            this.$message({
              type: 'success',
              message: `ID为${row.id}的数据删除成功!`
            });
            this.fetchData();
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
};
</script>

<style scoped>
.table-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>